package com.servengine.localizame;

import com.servengine.user.User;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import java.io.StringWriter;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class LocalizameConexion
{
	private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(LocalizameConexion.class.getName());
	String JSESSIONIDCookie;
	User user;
	String codigo;

	public LocalizameConexion(User user, String codigo) throws MalformedURLException, IOException
	{
		this.user=user;
		this.codigo=codigo;
	}

	private void setCommonRequestProperties(URLConnection connection)
	{
		connection.setRequestProperty("Accept-Language", "es");
		connection.setRequestProperty("Host", "www.localizame.movistar.es");
		connection.setRequestProperty("Accept-Encoding", "identity");
		connection.setRequestProperty("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*");
		connection.setRequestProperty("Connection", "Keep-Alive");
	}

	public LocalizamePosicion getPosicion() throws MalformedURLException, IOException
	{
	  try
		{
		  URL url=new URL("http://www.localizame.movistar.es/login.do");
		  URLConnection connection=url.openConnection();
		  setCommonRequestProperties(connection);
		  connection.setDoOutput(true);
		  OutputStreamWriter out=new OutputStreamWriter(connection.getOutputStream());
		  out.write("usuario="+user.getExtraUserdataMap().get("telefono")+"&clave="+codigo);
		  out.close();
		  JSESSIONIDCookie=connection.getHeaderField("Set-Cookie");
		  log.info("Invocada: "+url);
		  registraRespuesta(connection);

		  url=new URL("http://www.localizame.movistar.es/nuevousuario.do");
		  connection=url.openConnection();
		  connection.setRequestProperty("Cookie", JSESSIONIDCookie);
		  connection.setRequestProperty("Referer", "http://www.localizame.movistar.es/login.do");
		  setCommonRequestProperties(connection);
		  connection.connect();
		  log.info("Invocada: "+url);
		  registraRespuesta(connection);

		  url=new URL("http://www.localizame.movistar.es/insertalocalizador.do?telefono="+user.getExtraUserdataMap().get("telefono"));
		  connection=url.openConnection();
		  connection.setRequestProperty("Cookie", JSESSIONIDCookie);
		  connection.setRequestProperty("Referer", "http://www.localizame.movistar.es/buscalocalizadorespermisos.do");
		  setCommonRequestProperties(connection);
		  connection.connect();
		  log.info("Invocada: "+url);
		  registraRespuesta(connection);

			url=new URL("http://www.localizame.movistar.es/buscar.do");
			connection=url.openConnection();
			connection.setRequestProperty("Cookie", JSESSIONIDCookie);
			setCommonRequestProperties(connection);
			connection.setDoOutput(true);
			out=new OutputStreamWriter(connection.getOutputStream());
			out.write("telefono="+user.getExtraUserdataMap().get("telefono"));
			out.close();
		  log.info("Invocada: "+url);
			
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line = null;
			String telefono = user.getExtraUserdataMap().get("telefono");
			String codigoPostal;
			while ((line=in.readLine())!=null)
			{
				if (log.isDebugEnabled())
					log.debug(line);
				if (line.indexOf(telefono)>-1 && line.indexOf("CP")>0)
				{
					codigoPostal = line.substring(line.indexOf("CP")+3).split("\\.")[0];
					log.info(user.getId()+" situado en el codigo postal "+codigoPostal);
					in.close();
					return new LocalizamePosicion(user,codigoPostal);	
				}
			}
			in.close();
		} catch (Throwable e)
		{
			log.error(e.getMessage(),e);
		}
		return null;
	}

	public String registraRespuesta(URLConnection connection) throws IOException
	{
		StringWriter writer = new StringWriter();
		BufferedWriter bwriter = new BufferedWriter(writer);
	  if (log.isDebugEnabled())
	  {
	    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	    String line = null;
	    while ((line=in.readLine())!=null)
	    {
				if (log.isDebugEnabled())
					log.debug(line);
				bwriter.append(line);
				bwriter.newLine();
			}
	    in.close();
	  }
		return writer.toString();
	}
}
